package com.wbao.dianniu.ui;

import android.app.Dialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.arlen.photo.photopickup.presenter.PhotoPresenter;
import com.arlen.photo.photopickup.util.MediaUtils;
import com.arlen.photo.photopickup.view.ImageLookActivity;
import com.arlen.photo.photopickup.view.PhotoPickupActivity;
import com.arlen.photo.photopickup.widget.SimpleGrid;
import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.R;
import com.wbao.dianniu.customView.LoadingWaitDialog;
import com.wbao.dianniu.customView.NoDoubleClickListener;
import com.wbao.dianniu.data.QuestAnswerListData;
import com.wbao.dianniu.emojiUtils.EmotionMainFragment;
import com.wbao.dianniu.listener.IKnowAnswerAddListener;
import com.wbao.dianniu.listener.IQuestAnswerListener;
import com.wbao.dianniu.logical.Const;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.manager.KnowAnswerAddManger;
import com.wbao.dianniu.manager.QuestAnswerManager;
import com.wbao.dianniu.update.ErrorDialogHelper;
import com.wbao.dianniu.utils.ActivityUtils;
import com.wbao.dianniu.utils.AnswerListType;
import com.wbao.dianniu.utils.Notification;
import com.wbao.dianniu.utils.SerializableMap;
import com.wbao.dianniu.utils.Utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 带图片一级回复
 * <p>
 * Created by yejianjun on 2018/5/23.
 */

public class WithPicCommentActivity extends AppCompatActivity implements View.OnClickListener, IQuestAnswerListener, IKnowAnswerAddListener {
    private final int ASK_TYPE = 1;
    private ImageButton cancel;
    private Button submit;
    private EditText mEditText;
    private Dialog pDialog;
    private SimpleGrid mSimpleGrid;
    private PhotoPresenter mPhotoPresenter;
    private boolean isClick = false;
    private CheckBox checkBox;
    private ImageView picImage;
    private ImageView aFriendIV;
    private ImageView emojiBtn;
    private RelativeLayout mInfoRL;
    private EmotionMainFragment emotionMainFragment;
    private int REQ_CODE = 600;
    public static final String COMMENT_QUESTID = "intent.comment.questId";
    public static final String Comment_Content = "intent.comment.content";
    public static final String Comment_image_urls = "intent.comment.image.urls";
    public static final String Comment_notice_json = "intent.commnet.noticejson";
    public static final String Comment_type = "intent.type";
    // 问题回复管理类
    private QuestAnswerManager qAnswerManager;
    // 知识回复管理类
    private KnowAnswerAddManger knowAnswerAddManger;
    private int questId;
    private String answerImgs;
    private Map<Integer, String> noticeJson = new HashMap<Integer, String>();
    private int type;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityUtils.setStatusBarColor(this);

        setContentView(R.layout.activity_comment);
        mPhotoPresenter = new PhotoPresenter(this, "goods");
        initview();
        initData();
        changeStatus();
        initEmotionMainFragment();

    }

    private void changeStatus() {
        if (type == AnswerListType.TYPE_KNOW || type == AnswerListType.TYPE_QUEST) {
            checkBox.setButtonDrawable(R.drawable.xq_checkbox_unpress);
            checkBox.setClickable(false);
            checkBox.setChecked(false);
        } else if (type == AnswerListType.TYPE_AM) {
            if (!GlobalContext.getPerfectData()) {
                checkBox.setButtonDrawable(R.drawable.xq_checkbox_unpress_ok);
                checkBox.setChecked(true);
                checkBox.setClickable(false);
            } else {
                checkBox.setButtonDrawable(R.drawable.checkbox_style_xq);
                checkBox.setClickable(true);
            }
        }

    }


    /**
     * 初始化表情面板
     */
    public void initEmotionMainFragment() {
        //构建传递参数
        Bundle bundle = new Bundle();
        //绑定主内容编辑框
        bundle.putBoolean(EmotionMainFragment.BIND_TO_EDITTEXT, false);
        //隐藏控件
        bundle.putBoolean(EmotionMainFragment.HIDE_BAR_EDITTEXT_AND_BTN, true);
        //替换fragment
        //创建修改实例
        emotionMainFragment = EmotionMainFragment.newInstance(EmotionMainFragment.class, bundle);
        emotionMainFragment.bindToContentView(mInfoRL, emojiBtn, mEditText);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        // Replace whatever is in thefragment_container view with this fragment,
        // and add the transaction to the backstack
        transaction.replace(R.id.fl_emotionview_main, emotionMainFragment);
        transaction.addToBackStack(null);
        //提交修改
        transaction.commit();
    }

    private void initview() {
        ((TextView) findViewById(R.id.ask_title)).setText("回复");
        cancel = (ImageButton) findViewById(R.id.ask_back_button);
        submit = (Button) findViewById(R.id.ask_submit);

        mEditText = (EditText) findViewById(R.id.comment_editText);
        cancel.setOnClickListener(this);
        submit.setOnClickListener(new NoDoubleClickListener() {

            @Override
            public void onNoDoubleClick(View v) {
                // TODO Auto-generated method stub
                // 未完善资料，不能回复评论
                if (!GlobalContext.getPerfectData() && type != AnswerListType.TYPE_AM) {
                    ErrorDialogHelper.getInstance().showPerfectAuth(WithPicCommentActivity.this);
                    return;
                }
                String content;
                content = mEditText.getText().toString().trim();
                if (TextUtils.isEmpty(content)) {
                    Notification.showToastMsg(WithPicCommentActivity.this, "内容不能为空");
                    return;
                }
                if (mPhotoPresenter.isUploading()) {
                    Notification.showToastMsg(WithPicCommentActivity.this, "图片上传中，请稍后...");
                    return;
                }
                if (!isClick) {
                    isClick = true;
                    pDialog = LoadingWaitDialog.createLoadingDialog(WithPicCommentActivity.this, "");
                    pDialog.show();
//                    // 把图片列表转化成string
                    answerImgs = listToString(mPhotoPresenter.getSelectedList(), ',');
//                    // 去重noticeJson
                    String noticeJ = Utils.toHeavyNoticeJson(noticeJson, mEditText.getText().toString());
                    if (type == AnswerListType.TYPE_KNOW) {
                        knowAnswerAddManger.knowAnswerAdd(GlobalContext.getAccountId(), questId, content, noticeJ, answerImgs, 0, 0);
                    } else if (type == AnswerListType.TYPE_AM || type == AnswerListType.TYPE_QUEST) {
                        int anonymous;
                        if (type == AnswerListType.TYPE_QUEST) {
                            anonymous = 0;
                        } else {
                            if (checkBox.isChecked()) {
                                anonymous = 1;
                            } else {
                                anonymous = 0;
                            }
                        }
                        qAnswerManager.addResponse(GlobalContext.getAccountId(), questId, Utils.replaceLineBlanks(content), noticeJ, answerImgs, 0, anonymous);
                    }

                }
            }
        });

        mSimpleGrid = (SimpleGrid) findViewById(R.id.comment_img_grid);
        mPhotoPresenter.initView(mSimpleGrid);
        mSimpleGrid.setMaxItemPerRow(4);
        mSimpleGrid.setItemMarginHor(7f);
        mSimpleGrid.setItemMarginVer(7f);
        mPhotoPresenter.updateImgGrid();

        checkBox = (CheckBox) findViewById(R.id.am_release_checkbox);

        picImage = (ImageView) findViewById(R.id.bar_image_chose_pic);
        picImage.setOnClickListener(this);
        aFriendIV = (ImageView) findViewById(R.id.bar_image_a_friends);
        aFriendIV.setOnClickListener(this);

        mInfoRL = (RelativeLayout) findViewById(R.id.comment_rl);
        emojiBtn = (ImageView) findViewById(R.id.bar_image_add_btn);
    }

    private void initData() {
        Bundle bundle = getIntent().getExtras();

        questId = bundle.getInt(COMMENT_QUESTID, 0);
        String content = bundle.getString(Comment_Content);
        String urls = bundle.getString(Comment_image_urls);
        type = bundle.getInt(Comment_type);
        SerializableMap serializableMap = (SerializableMap) bundle.get(Comment_notice_json);
        noticeJson = serializableMap.getMap();
        if (!TextUtils.isEmpty(content)) {
            mEditText.setText(content);
        }
//        if (!TextUtils.isEmpty(urls)) {
//
//
//        }

        if (type == AnswerListType.TYPE_KNOW) {
            knowAnswerAddManger = KnowAnswerAddManger.getInstance(this);
            knowAnswerAddManger.addknowAnswerAddListener(this);
        } else if (type == AnswerListType.TYPE_AM || type == AnswerListType.TYPE_QUEST) {
            qAnswerManager = QuestAnswerManager.getInstance(this);
            qAnswerManager.addQuestAnswerListener(this);
        }


    }

    private String listToString(ArrayList<MediaUtils.ImageProperty> list, char separator) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            if (i == list.size() - 1) {
                sb.append(list.get(i).desc);
            } else {
                sb.append(list.get(i).desc);
                sb.append(separator);
            }
        }
        return sb.toString();
    }

    @Override
    public void onBackPressed() {
        /**
         * 判断是否拦截返回键操作
         */
        if (!emotionMainFragment.isInterceptBackPress()) {
            // 注释这段代码 这个会双击才能退出
            //super.onBackPressed();
            finish();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ask_back_button:
                finish();
                break;
            case R.id.bar_image_chose_pic:
                mPhotoPresenter.choseImage();
                break;
            case R.id.bar_image_a_friends:
                Intent aIntent = new Intent();
                aIntent.setClass(WithPicCommentActivity.this, SelectFriendActivity.class);
                startActivityForResult(aIntent, REQ_CODE);
                break;

            default:
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PhotoPickupActivity.REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                if (PhotoPickupActivity.getSelectedImgPros(data) != null) {
                    mPhotoPresenter.pickPhotoResult(data);
                }
            }
        } else if (requestCode == ImageLookActivity.REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                if (data != null) {
                    mPhotoPresenter.lookImageResult(data);
                }
            }
        } else if (requestCode == REQ_CODE) {
            if (resultCode == RESULT_OK) {
                String userName = data.getStringExtra(Const.INTENT_NICENAME);
                int friendId = data.getIntExtra(Const.BUNDLE_ACCOUNTID, 0);
                if (userName != null && 0 != friendId) {
                    noticeJson.put(friendId, userName);// 加入noticeJson
                    // 光标出插入@
                    int index = mEditText.getSelectionStart();
                    Editable editable = mEditText.getText();
                    editable.insert(index, "@" + userName);
                }
            }
        }
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != pDialog && pDialog.isShowing()) {
            pDialog.dismiss();
        }
        if (null != qAnswerManager) {
            qAnswerManager.removeQuestAnswerListener(this);
        }
        if (null != knowAnswerAddManger) {
            knowAnswerAddManger.removeknowAnswerAddListener(this);
        }
        // 移除绑定的EditText
        if (null != emotionMainFragment) {
            emotionMainFragment.removeEditText();
        }
    }

    @Override
    public void onQuestAnswerFailure(int errorCode, String errorMsg) {
        isClick = false;

    }

    @Override
    public void onQuestAnswerSuccess(QuestAnswerListData qacd) {
        isClick = false;
        finish();
    }


    @Override
    public void onKnowAnswerAddFailure(int errorCode, String errorMsg) {
        if (null != pDialog && pDialog.isShowing()) {
            pDialog.dismiss();
        }
        isClick = false;
    }

    @Override
    public void onKnowAnswerAddSuccess(QuestAnswerListData obj) {
        if (null != pDialog && pDialog.isShowing()) {
            pDialog.dismiss();
        }
        isClick = false;
        finish();
    }
}
